package org.atlantis.grosbeak.pot.dialect;

import org.atlantis.grosbeak.lang.Exceptions;
import org.atlantis.grosbeak.pot.PotException;

/**
 * HSQLDB数据库的方言。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
public class HSQLDBDialect implements Dialect {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.atlantis.grosbeak.pot.dialect.Dialect#bindLimitParametersFirst()
	 */
	public boolean bindLimitParametersFirst() {
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.atlantis.grosbeak.pot.dialect.Dialect#bindLimitParametersInReverseOrder
	 * ()
	 */
	public boolean bindLimitParametersInReverseOrder() {
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.atlantis.grosbeak.pot.dialect.Dialect#localizeLimitSQL(java.lang.
	 * String, boolean, boolean)
	 */
	public String localizeLimitSQL(String sql, boolean hasFirst, boolean hasMax) {
		StringBuilder sb = new StringBuilder(sql.length() + 30);
		sb.append(sql);
		int pos = sql.toLowerCase().indexOf("select");
		if (pos == -1)
			throw Exceptions.makeThrow(PotException.class,
					"The SQL syntax [%s] missing key word 'select'", sql);
		pos += 6;
		if (hasFirst && hasMax)
			sb.insert(pos, " limit ? ? ");
		else if (!hasFirst && hasMax)
			sb.insert(pos, " limit 0 ? ");
		else if (hasFirst && !hasMax)
			sb.insert(pos, " limit ? 2147483647 ");
		return sb.toString();
	}
}
